package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"im/app/models/form/user_group"
	validator2 "im/app/models/validator"
	"im/app/services"
	"im/app/util/response"
)

type UserGroup struct {

}

// 创建添加群
func (ug *UserGroup) Add(c *gin.Context) {
	inputs := user_group.UserGroupAdd{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	ugs := services.UserGroupService{}
	err = ugs.Add(inputs.GName, inputs.UserID)
	if err != nil {
		response.ReturnJsonOk(c, err.Error())
		return
	}

	response.ReturnJsonOk(c,"添加成功", nil)
}

// 加入群
func (u * UserGroup) JoinGroup(c *gin.Context) {
	inputs := user_group.UserGroupJoin{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	ugs := services.UserGroupService{}
	err = ugs.JoinGroup(inputs.GId, inputs.UserID, inputs.GName)
	if err != nil {
		response.ReturnJsonOk(c, err.Error())
		return
	}

	response.ReturnJsonOk(c,"加入群成功", nil)
}

// 退出群
func (u *UserGroup) OutGroup(c *gin.Context) {
	inputs := user_group.UserGroupJoin{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	ugs := services.UserGroupService{}
	err = ugs.OutGroupByGid(inputs.GId, inputs.UserID)
	if err != nil {
		response.ReturnJsonOk(c, err.Error())
		return
	}

	response.ReturnJsonOk(c,"退出群成功", nil)
}

// 搜索群
func (u *UserGroup) Search(c *gin.Context) {
	inputs := user_group.UserGroupSearch{
		GName:    "",
		Page:     1,
		PageSize: 10,
	}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	ugs := services.UserGroupService{}
	userGroups := ugs.Search(inputs.GName, inputs.Page, inputs.PageSize)

	response.ReturnJsonOk(c, "成功", userGroups)
}